/* ====================================== Select  ====================================== */
import React from 'react'
// ===================================================================== antd
import { Select } from 'antd'
// ===================================================================== Declare
const { $fn, $Lazy } = window
// ===================================================================== Lazy 
const Button = $Lazy.load(()=>import('@antd/button'))
// ===================================================================== 
class Index extends React.Component {
	state = {
		data:[],
		showSearch: true
	}
	
	_onChange = (value, option) => {
		const { name, onChanged, onChange, idStr, data, nameStr='name', outer } = this.props
		value = $fn.isValid(value) ? value : ''
		if(!outer){ this.setState({ value }) }
		
		let model = name ? { [name]: value } : value
		let rows = null
		
		const arr = data.filter( rows => rows[idStr || 'value'] === value)
		
		if ($fn.hasArray(arr)) { rows = arr[0] }
		
		this.label = rows?.[nameStr] ?? ''
		
		onChanged?.({ model, value, option, rows, name })
		onChange?.(value)
	}
	
	setValue = value => this.setState({ value })
	getValue = () => this.state.value
	
	clear = () => this.setState({ value: null, key:this.state.key+1 })
	
	onDropdownVisibleChange = value => {
		// setTimeout(()=>{
		// 	Array.prototype.slice.call(document.querySelectorAll('.ant-select-dropdown'),0).forEach(v=>{
		// 		v.addEventListener('mouseup',e => e.stopPropagation() )
		// 	})
		// }, 10);
		this.props?.onDropdownVisibleChange?.(value)
	}
	dropdownRender = menu => {
		const { dropdownRender } = this.props
		if (dropdownRender) {
			return <React.Fragment>{dropdownRender}</React.Fragment>
		} else {
			return <React.Fragment>{menu}</React.Fragment>
		}
	}
	inputKeyDown = (e) => {
		const { isKeydown } = this.props
		if (isKeydown === 'sex' || isKeydown === 'caseType') {
			this.setState( {showSearch:false})
		}
		document.addEventListener("keydown", this.handleKeyDown)
	}
	blur = () => {
		const { isKeydown } = this.props
		if (isKeydown === 'sex' || isKeydown === 'caseType') {
			this.setState({showSearch:true})
		}
		document.removeEventListener("keydown", this.handleKeyDown)
	}
	handleKeyDown = e => {
		const { onChange, data, idStr='value', isKeydown } = this.props
		const code = e.code
		let index
		let value
		if(code.indexOf('Digit') !== -1 || code.indexOf('Numpad') !== -1){
			if (code.indexOf('Digit') === -1){
				index = +e.code.replace('Numpad','')
			}else if(code.indexOf('Numpad') === -1){
				index = +e.code.replace('Digit','')
			}
			if(isKeydown === 'sex'){
				switch (index) {
					case 1:
						value = '45701'
						break;
					case 2:
						value = '45702'
						break;
					case 3:
						value = '45703'
						break;
					default:
						break;
				}
			}else{
				const number = data.length > 10 ? 10 : data.length
				if( index >= 0 && index <= number ){
					if( index === 0) {
						data[9] && (value = data[9][idStr])
					} else {
						value = (data[index - 1][idStr])
					}
				}
			}
			onChange?.(value)
		}
		if (isKeydown === 'kind') {
			if (data.length) {
				let activeElement = document.querySelector(".kindSelect .click-active")
				if (!activeElement) {
					activeElement = document.querySelectorAll('.kindSelect tr[index]')[0]
					activeElement?.setAttribute("class", "ant-table-row ant-table-row-level-0 click-active")
				} else {
					if(code === 'ArrowUp'){
						if (activeElement.attributes.index.value) {
							const elements = document.querySelectorAll('.kindSelect tr[index]')
							elements.forEach((v, i) => {
								if (v.attributes.index.value === (+activeElement.attributes.index.value - 1).toString()) {
									v.setAttribute("class", "ant-table-row ant-table-row-level-0 click-active")
									if (i < 2) {
										document.querySelector('.kindSelect .ant-table-body').scrollTop = (+v.attributes.index.value - 1) * 39
									}
								} else {
									v.setAttribute("class", "ant-table-row ant-table-row-level-0")
								}
							})
						}
					}
					if(code === 'ArrowDown'){
						if (activeElement.attributes.index.value) {
							const elements = document.querySelectorAll('.kindSelect tr[index]')
							elements.forEach((v, i) => {
								if (v.attributes.index.value === (+activeElement.attributes.index.value + 1).toString()) {
									v.setAttribute("class", "ant-table-row ant-table-row-level-0 click-active")
									if (i > 5) {
										document.querySelector('.kindSelect .ant-table-body').scrollTop = (+v.attributes.index.value - 1) * 39
									}
								} else {
									v.setAttribute("class", "ant-table-row ant-table-row-level-0")
								}
							})
						}
					}
					if(code === 'Enter'|| code === 'NumpadEnter') {
						document.querySelector(".kindSelect .click-active").click()
						this.blur()
					}
				}
			}
		}
	}
	
	render(){
		let { data, value, idStr='value', nameStr='name', count=1, p, btn, width, size, style,isP, afterSuffix, noSearch,
			className, mode, disabled, loading, bordered, auto, isClear, dropdownRender, open, onClick, onSearch, icon, isKeydown, copy, tipTxt
		} = this.props
		const { key, showSearch } = this.state
		let _data = data || this.state.data
		let t = p ? p : ''
		const borderedValue = bordered === false ? false : true
		const _size = size || 'small'
		let _value = this.state.value === undefined ? value : this.state.value
		const AfterSuffix = typeof afterSuffix === 'function' ? afterSuffix() : afterSuffix
		// 测试提示
		const txt = dropdownRender ? null : tipTxt ? tipTxt: $fn.formTest(data, idStr, nameStr)
		
		return (
			<div className='fxm ex' onClick={e=> e.stopPropagation()} onDoubleClick={e=> e.stopPropagation()}>
				<Select 
					ref			= { ref => this.selectRef = ref }
					key 		= { key }
					size		= { _size } 
					onChange	= { this._onChange } 
					style		= {{ minWidth:width, ...style }} 
					value 		= { _value === '' ? null : _value }
					className 	= {`${className?className:'w'} ${bordered===false ? 'input-bordered':''}`}
					placeholder	= { txt ? txt : (isP ? '请选择' + t :  t)  }
					disabled	= { (!$fn.hasArray(data) && !dropdownRender) || disabled }
					mode		= { mode }
					loading		= { loading }
					bordered	= { borderedValue }
					showSearch	= { noSearch !== undefined ? !noSearch : showSearch }
					allowClear  = { isClear !== false }
					open		= { open }
					
					onDropdownVisibleChange 	= {this.onDropdownVisibleChange}
					dropdownClassName 			= { _size === 'small' ? 'dropdown-small' : ''}
					dropdownMatchSelectWidth 	= {auto ? false : true}
					filterOption 		= { !dropdownRender ? (inputValue, option)=>{
						const value = option.children[1].indexOf(inputValue)
						return value !== -1
					} : null }
					dropdownRender 		= {this.dropdownRender}
					maxTagCount 		= { count }
					// maxTagPlaceholder 	= { omittedValues => {
					// 	return '+' + _value.length
					// } }
					onClick				= { e => {
						e.stopPropagation()
						onClick?.()
					} }
					onSearch			= { onSearch }
					onInputKeyDown		= { isKeydown ? this.inputKeyDown : null }
					onBlur				= { isKeydown ? this.blur : null }
				>
					{
						$fn.hasArray(_data) && _data.map((v,i)=>{
							return (
								<React.Fragment key={i}> 
									{
										v.group ? (
											<Select.OptGroup key={i} label={v.group}>
												{
													$fn.hasArray(v.children) && v.children.map((p, j) => <Select.Option key={p[idStr]} value={p[idStr]} style={{marginRight:'20px'}}>{p[nameStr]}</Select.Option>)
												}
											</Select.OptGroup>
										): (
											<Select.Option key={i} value={v[idStr]} style={{marginRight:'20px'}}>
												{
													icon && <i className={`iconfont icon${v[nameStr]} mr5 rel vt`}  style={{top:1}}></i>
												}
												{v[nameStr]}
											</Select.Option>
										)
									}
								</React.Fragment>
							)
						})
					}
				</Select>
				{
					$fn.hasObject(btn) && <Button className='ml10' {...btn} disabled={btn.disabled !== undefined ? btn.disabled : disabled} onClick={()=> btn.onClick && btn.onClick(value)} />
				}
				{ AfterSuffix }
				{
					copy && <Button className='ml5' label='复制' onClick={()=>$fn.copyText( this.label )}/>
				}
			</div>
		)
	}
}
export default Index